package com.liangtian.mdm.system.file.service.impl;

import com.liangtian.mdm.base.exception.BaseRuntimeException;
import com.liangtian.mdm.system.file.model.SysFile;
import com.liangtian.mdm.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import static com.liangtian.mdm.base.constants.ResultCode.FTP_ERROR;

/**
 * Created by admin on 2017/9/25.
 */
@Service

public class SysFileToFtpServiceImpl extends SysFileServiceSuper {
    private static Logger log = LoggerFactory.getLogger(SysFileToFtpServiceImpl.class);

    @Override
    public Map<String, Object> insertFile(HttpServletRequest request, Map<String, Object> Fcond) {
        Map<String, Object> resMap = new HashMap<>();
        boolean success = true;
        List<String> fileNameLst = new ArrayList<String>();
        String[] ftpstres = checkFtpInfo(); //验证格式

        String surveyType = (String) Fcond.get("surveyType"); //方便测试，后期从页面获取所属业务
        String surveyName = (String) Fcond.get("surveyName");
        String dataId = (String) Fcond.get("dataId");
        String operType = (String) Fcond.get("operType");

        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            MultiValueMap<String, MultipartFile> map = multiRequest.getMultiFileMap();
            Set<Map.Entry<String, List<MultipartFile>>> mapSet = map.entrySet();
            String keyColumn = null;//附件的列名,如:c_001,c_002
            int count = 0;
            for (Map.Entry<String, List<MultipartFile>> entry : mapSet) {
                keyColumn = entry.getKey();
                count = charCount(keyColumn, '_');
                if (2 == count)
                    keyColumn = keyColumn.substring(0, keyColumn.lastIndexOf("_"));
                //取得上传文件
                MultipartFile file = entry.getValue().get(0);
                if (file != null) {
                    String myFileName = file.getOriginalFilename();
                    if (myFileName.trim() != "") {//文件存在
                        fileNameLst.add(myFileName);
                        //文件路径
                        String path = "/" + surveyName + "/" + new Date().getTime() + "/" + myFileName;
                        try {
                            InputStream inputStream = file.getInputStream();
                            success = FileUtil.ftpUploadFile(ftpstres[0], new Integer(ftpstres[1]), ftpstres[2], ftpstres[3], path, myFileName, inputStream);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        this.insertFileInfo(myFileName, path, file.getSize(), surveyType, dataId, keyColumn, operType);
                    }
                }
            }
        }
        resMap.put("IsSuccess", success);
        resMap.put("FileNameLst", fileNameLst);
        return resMap;

    }


    @Override
    public void delFileByPath(SysFile file) {
        String[] tpstres = checkFtpInfo();
        FileUtil.ftpDeleteFile(tpstres[0], new Integer(tpstres[1]), tpstres[2], tpstres[3], file.getFilePath());
        sysFileDao.fileDel(file.getId());//删除附件表的信息

    }

    @Override
    public void delFileByPath(List<SysFile> fileLst) {
        for (SysFile sysFile :
                fileLst) {
            this.delFileByPath(sysFile);
        }
    }


    public String[] checkFtpInfo() {
        String ftpInfo = sysParameterService.getSysParamValue("ftpInfo", "null");
        if ("null".equals(ftpInfo)) {
            throw new BaseRuntimeException(FTP_ERROR.getCode(), "未设置Ftp信息");
        }
        String[] ftpstres = ftpInfo.split(":");
        if (ftpstres.length != 4) {
            throw new BaseRuntimeException(FTP_ERROR.getCode(), "格式错误,正确格式 url:port:username:uuserps");
        }
        return ftpstres;
    }

    @Override
    public Map<String, Object> insertSysContentFile(HttpServletRequest request, Map<String, Object> Fcond) {
        Map<String, Object> resMap = new HashMap<>();
        boolean success = true;
        List<String> fileNameLst = new ArrayList<>();
        String[] ftpstres = checkFtpInfo(); //验证格式
        try {
            String surveyType = (String) Fcond.get("surveyType"); //方便测试，后期从页面获取所属业务
            String surveyName = (String) Fcond.get("surveyName");
            String dataId = (String) Fcond.get("dataId");
            String operType = (String) Fcond.get("operType");
            List<String> fileList = (List<String>) Fcond.get("fileList");
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            if (multipartResolver.isMultipart(request)) {
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                MultiValueMap<String, MultipartFile> map = multiRequest.getMultiFileMap();
                Set<Map.Entry<String, List<MultipartFile>>> mapSet = map.entrySet();
                for (Map.Entry<String, List<MultipartFile>> entry : mapSet) {
                    MultipartFile file = entry.getValue().get(0);
                    if (file != null) {
                        //取得当前上传文件的文件名称
                        String myFileName = file.getOriginalFilename();
                        String keyColumn = fileList.get(0).trim();//赋值的是版本号
                        if (myFileName.trim() != "") {
                            fileNameLst.add(myFileName);
                            String path = "/" + surveyName + "/" + new Date().getTime() + "/" + myFileName;
                            try {
                                InputStream inputStream = file.getInputStream();
                                success = FileUtil.ftpUploadFile(ftpstres[0], new Integer(ftpstres[1]), ftpstres[2], ftpstres[3], path, myFileName, inputStream);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            this.insertFileInfo(myFileName, path, file.getSize(), surveyType, dataId, keyColumn, operType);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }
        resMap.put("IsSuccess", success);
        resMap.put("FileNameLst", fileNameLst);
        return resMap;
    }


}
